<?php


namespace application\component;


use modules\sys\component\GetCacheComponent;

class DataComponent
{

    /**
     * 获取db-table 的字段映射数据
     * @param $value
     * @param $res
     * @param string $split
     * @return array
     */
    public static function getDbField($value, $res, string $split = ","): array
    {
        if(empty($value)){
            return [];
        }
        $valueArr = explode($split, $value);
        if (empty($valueArr)) {
            return [];
        }
        $resArr = [];
        foreach ($valueArr as $field) {
            if ($res[$field]) {
                $resArr[] = $res[$field];
            }
        }
        return $resArr;
    }

    /**
     * 获取字典标签的数据
     * @param $value
     * @param $dictCode
     * @param string $split
     * @return array
     */
    public static function getDictData($value, $dictCode, string $split = ","): array
    {
        if(empty($value)){
            return [];
        }
        $valueArr = explode($split, $value);
        if (empty($valueArr)) {
            return [];
        }
        static $dictDataRes = [];
        //这里判断一下，避免循环中调用
        if (empty($dictDataRes)) {
            //从redis或数据库中加载数据字典缓存
            $dictDataRes = GetCacheComponent::dictData();
        }
        $resArr = [];
        foreach ($dictDataRes as $v) {
            if ($v['dict_code'] == $dictCode) {
                if (in_array($v['dict_value'], $valueArr)) {
                    $resArr[] = $v;
                }
            }
        }
        return $resArr;
    }

    /**
     * 获取catalog 数据
     * @param $value
     * @param string $split
     * @return array
     */
    public static function getCatalog($value, string $split = ","): array
    {
        if(empty($value)){
            return [];
        }
        $valueArr = explode($split, $value);
        if (empty($valueArr)) {
            return [];
        }
        static $catalogRes = [];
        //这里判断一下，避免循环中调用
        if (empty($catalogRes)) {
            //从redis或数据库中加载目录缓存
            $catalogRes = GetCacheComponent::catalog();
        }
        $resArr = [];
        foreach ($catalogRes as $v) {
            if (in_array($v['id'], $valueArr)) {
                $resArr[] = $v;
            }
        }
        return $resArr;
    }
}